Completed
Pull Request — master (#226)
by
unknown
34s
created

EAN8.js ➔ ???   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A EAN8.js ➔ ... ➔ ??? 0 1 1
1
// Encoding documentation:
2
// http://www.barcodeisland.com/ean8.phtml
3
4
import { SIDE_BIN, MIDDLE_BIN } from './constants';
5
import encode from './encoder';
6
import Barcode from "../Barcode";
7
8
// Calculate the checksum digit
9
const checksum = (number) => {
10
	const res = number
11
		.substr(0, 7)
12
		.split('')
13
		.map((n) => +n)
14
		.reduce((sum, a, idx) => {
15
			return idx % 2
16
				? sum + a
17
				: sum + a * 3;
18
		}, 0);
19
20
	return (10 - (res % 10)) % 10;
21
};
22
23
class EAN8 extends Barcode {
24
25
	constructor(data, options) {
26
		// Add checksum if it does not exist
27
		if(data.search(/^[0-9]{7}$/) !== -1){
28
			data += checksum(data);
29
		}
30
31
		super(data, options);
32
	}
33
34
	valid() {
35
		return (
36
			this.data.search(/^[0-9]{8}$/) !== -1 &&
37
			+this.data[7] === checksum(this.data)
38
		);
39
	}
40
41
	get leftData() {
42
		return this.data.substr(0, 4);
43
	}
44
45
	get rightData() {
46
		return this.data.substr(4, 4);
47
	}
48
49
	encode() {
50
		const data = [
51
			SIDE_BIN,
52
			encode(this.leftData, 'LLLL'),
53
			MIDDLE_BIN,
54
			encode(this.rightData, 'RRRR'),
55
			SIDE_BIN,
56
		];
57
58
		return {
59
			data: data.join(''),
60
			text: this.text
61
		};
62
	}
63
64
}
65
66
export default EAN8;
67